package org.study.minio.boot.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.*;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.study.minio.boot.util.AwsUtils;

/**
 * aws-s3通用存储操作，支持所有兼容s3协议的云存储：阿里云OSS、腾讯云COS、七牛云、京东云、minio等
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年11月25日
 */
@Configuration
@EnableConfigurationProperties(AwsProperties.class)
public class AwsConfig {
    @Bean
    public AmazonS3 amazonS3(AwsProperties awsProperties) {
        ClientConfiguration clientConfig = new ClientConfiguration();
        // 默认HTTPS
        clientConfig.setProtocol(Protocol.HTTP);
        // clientConfig.setMaxConnections(ClientConfiguration.DEFAULT_MAX_CONNECTIONS);
        clientConfig.setMaxConnections(awsProperties.getMaxConnections());
        clientConfig.setConnectionTimeout(ClientConfiguration.DEFAULT_CONNECTION_TIMEOUT);
        // v2-S3SignerType，v4-AWSS3V4SignerType
        clientConfig.setSignerOverride("S3SignerType");

        AWSCredentials credentials = new BasicAWSCredentials(awsProperties.getAccessKey(), awsProperties.getSecretKey());
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);

        // AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(awsProperties.getEndpoint(), null);
        // AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(awsProperties.getEndpoint(), awsProperties.getRegion());
        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(awsProperties.getEndpoint(), Regions.CN_NORTH_1.name());

        AmazonS3 amazonS31 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(clientConfig)
                .withCredentials(credentialsProvider)
                .withPathStyleAccessEnabled(awsProperties.getPathStyleAccessEnabled())
                .disableChunkedEncoding()
                .build();

        AmazonS3 amazonS32 = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(clientConfig)
                .withCredentials(credentialsProvider)
                .withPathStyleAccessEnabled(awsProperties.getPathStyleAccessEnabled())
                .withChunkedEncodingDisabled(true)
                .build();

        // 给工具类注入它需要的Bean
        AwsUtils.init(awsProperties, amazonS31);
        return amazonS31;
    }
}
